package com.small.admin.service.impl;

import com.small.admin.dto.DictionariesChilds;
import org.springframework.stereotype.Service;
import com.small.common.base.service.impl.BaseServiceImpl;
import com.small.admin.entity.Dictionaries;
import com.small.admin.mapper.DictionariesMapper;
import com.small.admin.service.DictionariesService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 作者: fenny
 * 邮箱: 893146555@qq.com
 * 时间: 2017-11-01 08:40:33
 * 描述: 字典
 */
@Service
public class DictionariesServiceImpl extends BaseServiceImpl<DictionariesMapper, Dictionaries> implements DictionariesService {
    @Override
    public List<Dictionaries> selectByParentId(Long parentId) {
        return mapper.selectByParentId(parentId);
    }

    @Override
    public Map<String, List<DictionariesChilds>> selectRecursionByParentId(Long parentId) {
        return recursion(parentId);
    }

    @Override
    public Map<String,Dictionaries> selectRecursionMapByParentId(Long parentId) {
        Map<String,Dictionaries> dictionariesMap = new HashMap<>();
        recursionMap(dictionariesMap, parentId);
        return dictionariesMap;
    }

    /**
     * 递归字典
     *
     * @param parentId 父节点
     * @return 指定父节点下的所有子节点
     */
    private Map<String, List<DictionariesChilds>> recursion(Long parentId) {
        List<Dictionaries> dics = mapper.selectByParentId(parentId);
        Map<String, List<DictionariesChilds>> childsMap = new HashMap<>();
        List<DictionariesChilds> dictionariesChildsList = new ArrayList<>();
        DictionariesChilds childs;
        for (Dictionaries dic : dics) {
            childs = new DictionariesChilds();
            childs.setId(dic.getId());
            childs.setName(dic.getName());
            childs.setParentId(dic.getParentId());
            childs.setChildsMap(recursion(dic.getId()));
            dictionariesChildsList.add(childs);
        }
        childsMap.put(String.valueOf(parentId), dictionariesChildsList);
        return childsMap;
    }

    /**
     * 递归字典
     * @param dictionariesMap map
     * @param parentId 父级ID
     */
    private void recursionMap(Map<String,Dictionaries> dictionariesMap, Long parentId) {
        List<Dictionaries> dics = mapper.selectByParentId(parentId);
        for (Dictionaries dic : dics) {
            dictionariesMap.put(String.valueOf(dic.getId()),dic);
            recursionMap(dictionariesMap, dic.getId());
        }
    }
}